﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 定义一个多边形ui点击区域
    /// </summary>
    [RequireComponent(typeof(PolygonCollider2D))]
    public sealed class UIBlockPolygon : Graphic,ICanvasRaycastFilter
    {
        private PolygonCollider2D polygoncol;
        private PolygonCollider2D polygonCollider2D
        {
            get
            {
                if (polygoncol == null) polygoncol = GetComponent<PolygonCollider2D>();
                return polygoncol;
            }
        }
        public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
        {
            if(eventCamera != null)
            {
                Vector3 vector;
                return RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, sp, eventCamera, out vector)
                    && polygonCollider2D.OverlapPoint(vector);
            }
            return polygonCollider2D.OverlapPoint(sp);
        }

        /// <summary>
        /// 清除所有顶点
        /// </summary>
        /// <param name="vh"></param>
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
        }

        /// <summary>
        /// 不渲染texture
        /// </summary>
        public override Texture mainTexture
        {
            get
            {
                return null;
            }
        }
        /// <summary>
        /// 不传送mat去渲染
        /// </summary>
        public override Material materialForRendering
        {
            get
            {
                return null;
            }
        }

#if UNITY_EDITOR
        /// <summary>
        /// 组件菜单Reset命令，复位编辑的多边形为正方形初始状态
        /// </summary>
        protected override void Reset()
        {
            base.Reset();
            transform.localPosition = Vector3.zero;
            float _x = rectTransform.sizeDelta.x * 0.5f + 0.1f;
            float _y = rectTransform.sizeDelta.y * 0.5f + 0.1f;
            polygonCollider2D.points = new Vector2[]
            {
                new Vector2(-_x, -_y),
                new Vector2(_x, -_y),
                new Vector2(_x, _y),
                new Vector2(-_x, _y)
            };

        }
#endif

    }

}

